/*
 * @(#)TestsetTranslator.java
 *
 *
 *
 * ver 1.0 Sep 4, 2007 ggranum
 */
package org.testfire.realm.view.json.translator;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.testfire.realm.model.entities.testfire.TestsetResultEntity;
import org.testfire.realm.util.json.JsonField;
import org.testfire.realm.util.json.Tools;
import org.testfire.realm.view.tags.util.JavaScriptUtilities;

// eof: TestsetTranslator.java

/**
 * Application Scope
 *
 */
public class TestsetResultTranslator implements JsonTranslator<TestsetResultEntity>
{

    static final List<JsonField> ALL_FIELDS = new ArrayList<JsonField>();

    static
    {
        ALL_FIELDS.add( new JsonField( "id", JsonField.TYPE_INT ) );
        ALL_FIELDS.add( new JsonField( "started", JsonField.TYPE_DATE ) );
        ALL_FIELDS.add( new JsonField( "failureCount", JsonField.TYPE_INT ) );
        ALL_FIELDS.add( new JsonField( "runTime", JsonField.TYPE_INT ) );
        ALL_FIELDS.add( new JsonField( "errorMessage", JsonField.TYPE_STRING ) );
    }

    public String toJson( TestsetResultEntity object )
    {
        return Tools.getJsonString( object, ALL_FIELDS );
    }

    public String toJson( TestsetResultEntity object, String fields ) throws JSONException
    {
        return Tools.getJsonString( object, fields );
    }

    public String toJson( List<TestsetResultEntity> objects )
    {
        return Tools.getJsonString( objects, ALL_FIELDS );
    }

    public String toJsonArray( List<TestsetResultEntity> objects, String fields ) throws JSONException
    {
        return Tools.getJsonString( objects, fields );
    }

    public TestsetResultEntity toObject( String json ) throws JSONException
    {
        JSONObject obj = new JSONObject( json );
        TestsetResultEntity result = new TestsetResultEntity();
        int id = (Integer)obj.get( "id" );
        Date started;
        try
        {
            started = JavaScriptUtilities.toDateTime( (String)obj.get( "started" ) );
        }
        catch ( ParseException e )
        {
            throw new RuntimeException( e );

        }
        result.setId( id );
        result.setStarted( new Timestamp( started.getTime() ) );

        result.setFailureCount( (Integer)obj.get( "failurecount" ) );
        result.setErrorMessage( (String)obj.get( "errormessage" ) );
        result.setRunTime( (Integer)obj.get( "runtime" ) );
        return result;
    }

    public TestsetResultEntity copyValues( TestsetResultEntity to, TestsetResultEntity from )
    {
        to.setStarted( from.getStarted() );
        to.setErrorMessage( from.getErrorMessage() );
        to.setRunTime( from.getRunTime() );
        // don't set id
        to.setFailureCount( from.getFailureCount() );
        // all other setters are for collections, not directly editable by user.
        return to;
    }


}